package arina.university.dao.impl.memory;

import arina.university.dao.StudentDAO;
import arina.university.errorhandling.DAOException;
import arina.university.model.Student;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * User: user
 * Date: 26.11.13
 * Time: 15:47
 * To change this template use File | Settings | File Templates.
 */
// todo arina: сделала свой класс исключений, перенесла их все сюда

public class MemoryStudentDAO implements StudentDAO {
    private Map<Integer, Student> students = new HashMap<Integer, Student>();  // todo arina: изменила HashSet на HashMap
    static private MemoryStudentDAO memoryStudentDAO;

    private MemoryStudentDAO() {
    }

    public static MemoryStudentDAO getInstance() {
        if (memoryStudentDAO == null) {
            memoryStudentDAO = new MemoryStudentDAO();
        }
        return memoryStudentDAO;

    }


    public boolean checkExistence(int id){
        if (students.containsKey(id)) {return true;}        // todo arina: добавила метод проверки существования
        else return false;


    }
    @Override
    public Student create(String name, int id, String enterDate) throws DAOException {
         if(checkExistence(id)){                                                         // todo arina: в каждом методе проверяю существоание перед тем как что-то делать или создавать
             throw new DAOException("Student with such ID has already been created");
         }
        Student student = new Student(name, id, enterDate);
        students.put(student.getId(), student);
        return student;
    }


    @Override
    public void delete(int id) throws DAOException {
        if(!checkExistence(id)) {
            throw new DAOException("There is no such student");
        }
        students.remove(id);
    }

    @Override
    public void save(Student student) throws DAOException {
        if(checkExistence(student.getId())){
            throw new DAOException("Student with such ID already exists");
        }

        students.put(student.getId(), student);
    }

    @Override
    public Student find(int id) throws DAOException {
        if(!checkExistence(id)){
            throw new DAOException("There is no such student");
        }
        return students.get(id);

    }

    @Override
    public Collection<Student> findAll() throws DAOException {
        if (students.values().isEmpty()){
            throw new DAOException("You have no students");
        }
        return students.values();
    }
}
